const express = require('express')
const multer = require('multer')
const fs = require('fs')
const router = express.Router()


const Blog = require('../../models/Blog')

// 添加博客
router.post('/add', multer({
  dest: 'asset/imgs'
}).single('photo'), (req, res) => {
  const blogText = {}
  fs.renameSync(req.file.path, `asset/imgs/${req.file.originalname}`)
  req.body.url = req.file.originalname
  // req.body.url ? res.download(`asset/imgs/${req.body.url}`) : res.send({
  //   success: false
  // })
  blogText.imgUrl = 'http://localhost:5000/api/blog/img?url=' + req.body.url
  blogText.title = req.body.title
  blogText.text = req.body.text
  console.log(blogText)
  new Blog(blogText).save().then(blog => {
    res.json(blog)
  })
});
// 博客图片
router.get('/img', (req, res) => {
  req.query.url ? res.download(`asset/imgs/${req.query.url}`) : res.send({
    success: false
  })
})

// 删除博客
router.delete('/delete/:id', (req, res) => {
  Blog.findOneAndRemove({
    _id: req.params.id
  }).then(blog => res.json(blog))
    .catch(err => res.status(404).json('删除失败'))
})


//查询博客
router.get('/', (req, res) => {
  Blog.find()
    .then(Blog => {
      if (!Blog) {
        return res.status(404).json('没有任何内容')
      }
      res.json(Blog)
    })
    .catch(err => res.status(404).json(err))
})

//查询单个博客
router.get('/:id', (req, res) => {
  console.log(req)
  Blog.findOne({
    _id: req.params.id
  })
    .then(blog => {
      if (!blog) {
        return res.status(404).json('没有任何内容')
      }
      res.json(blog)
    })
    .catch(err => res.status(404).json(err))
})

//关键词搜索
router.post('/search', (req, res) => {
  Blog.find(
    {title: {$regex: req.body.keyword, $options: 'i'}}
  )
    .then(blog => {
      if (!blog) {
        return res.status(404).json('没有任何内容')
      }
      res.json(blog)
    })
    .catch(err => res.status(404).json(err))
})

//赞
router.post('/fabulous/:id', (req, res) => {
  console.log(req.body)
  Blog.findOneAndUpdate({
    _id: req.params.id
  }, {
    $set: {
      top: req.body.top
    }
  }, {
    new: true
  }).then(() => res.json('ok'))
})

//踩
router.post('/step/:id', (req, res) => {
  Blog.findOneAndUpdate({
    _id: req.params.id
  }, {
    $set: {
      trample: req.body.trample
    }
  }, {
    new: true
  }).then(() => res.json('ok'))
})


module.exports = router